/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.unifei.portal.dao;

import br.edu.unifei.portal.modelo.Empresa;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 *
 * @author Cristiano Affá
 */
public class EmpresaDao {

    private EntityManager em;

    public EmpresaDao(EntityManager em) {
        this.em = em;
    }

    public void create(Empresa empresa) {
        em.getTransaction().begin();
        em.persist(empresa);
        em.getTransaction().commit();
    }

    public void update(Empresa empresa) {
        em.getTransaction().begin();
        em.merge(empresa);
        em.getTransaction().commit();
    }

    public void delete(String cnpj) {
        em.getTransaction().begin();
        Empresa c = findEmpresa(cnpj);
        em.remove(c);
        em.getTransaction().commit();
    }

    public Empresa findEmpresa(String cnpj) {
        return (Empresa) em.createQuery(
                "from Empresa where cnpj = '" + cnpj + "'").getSingleResult();
    }

    public List<Empresa> findAllEmpresa() {
        return em.createQuery("from Empresa").getResultList();
    }

    public List<Empresa> findPageEmpresa(int max, int first) {
        Query query = em.createQuery("from Empresa");
        query.setMaxResults(max);
        query.setFirstResult(first);
        return query.getResultList();
    }

    public long getCountEmpresa() {
        Query query = em.createQuery("from Empresa");
        return (Long) em.createQuery(
                "select count(*) from Empresa").getSingleResult();
    }
}
